package com.xiong.wuliao.homeweather;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.xiong.wuliao.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class WeatherActivity extends AppCompatActivity {
	private ImageButton search_iv;
	private TextView city_tv;
	private TextView pm_tv;
	private View view_bottomLine;
	private TextView temp_tv;
	private TextView error_tv;
	private TextView weather_tv;
	private TextView wind_tv;
	private TextView date_tv;
	private List<String> list;
	private Handler handler;
	private LinearLayout other_ll;
	private ImageButton myButtonWeatherBack; // 返回按钮

	private int code;
	private String url;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_weather);

		url = "http://weather.123.duba.net/static/weather_info/";
		SharedPreferences preferences = getSharedPreferences("Boring", MODE_PRIVATE);
		code = preferences.getInt("CityCode", 101270101);

		initView(); // 初始化
		getData(code); // 网络
		initData();
		initHander();
		setListener();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	private void saveCode(int code) {
		SharedPreferences preferences = getSharedPreferences("Boring", MODE_PRIVATE);
		SharedPreferences.Editor editor = preferences.edit();
		editor.putInt("CityCode", code);
		editor.commit();
	}

	private void setListener() {
		search_iv.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(WeatherActivity.this, SearchActivity.class);
				// 带返回值的跳转页面，可以将要跳转的页面中的数据传回来
				startActivityForResult(intent, 100);
			}
		});
		myButtonWeatherBack.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				WeatherActivity.this.finish();
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		code = resultCode;
		if (code >= 100000000) {
			saveCode(code);
			getData(code);
		}
	}

	private void initHander() {
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				if (msg.what == 404) {
					error_tv.setText("网络错误，请检查网络");
				} else if (msg.what == 200) {// 数据加载成功
					error_tv.setText("");
					error_tv.setText("");
					List<WeatherBean> list = (List<WeatherBean>) msg.obj;
					WeatherBean bean = list.get(0);
					// 更新UI
					city_tv.setText(bean.getCity());
					pm_tv.setText(bean.getPm());
					temp_tv.setText(bean.getTempCurrent());
					weather_tv.setText(bean.getWeather() + bean.getTemp());
					wind_tv.setText(bean.getWindCurrent());
					date_tv.setText(bean.getDate_y() + " " + bean.getWeek());

					// 设置根据PM的大小来显示不同的颜色
					String pm = bean.getPm();
					if (pm.contains(getResources().getString(R.string.pm1))) {
						view_bottomLine.setBackgroundColor(getResources().getColor(R.color.pm1));
					} else if (pm.contains(getResources().getString(R.string.pm2))) {
						view_bottomLine.setBackgroundColor(getResources().getColor(R.color.pm2));
					} else if (pm.contains(getResources().getString(R.string.pm3))) {
						view_bottomLine.setBackgroundColor(getResources().getColor(R.color.pm3));
					} else if (pm.contains(getResources().getString(R.string.pm4))) {
						view_bottomLine.setBackgroundColor(getResources().getColor(R.color.pm4));
					} else if (pm.contains(getResources().getString(R.string.pm5))) {
						view_bottomLine.setBackgroundColor(getResources().getColor(R.color.pm5));
					} else if (pm.contains(getResources().getString(R.string.pm6))) {
						view_bottomLine.setBackgroundColor(getResources().getColor(R.color.pm6));
					} else {
						view_bottomLine.setBackgroundColor(getResources().getColor(R.color.pm7));
					}
					// 清空所有之前的孩子
					other_ll.removeAllViews();

					// 后五天的天气情况,for循环动态的在otherLayout中添加View
					for (int i = 1; i < list.size(); i++) {
						WeatherBean weatherBean = list.get(i);
						View view = LayoutInflater.from(WeatherActivity.this).inflate(R.layout.item, null);
						TextView week_tv = (TextView) view.findViewById(R.id.week_item_tv);
						TextView weather_tv = (TextView) view.findViewById(R.id.weather_item_tv);
						TextView temp_tv = (TextView) view.findViewById(R.id.temp_item_tv);

						// 给控件赋值
						week_tv.setText(weatherBean.getWeek());
						weather_tv.setText(weatherBean.getWeather());
						temp_tv.setText(weatherBean.getTemp());
						other_ll.addView(view);
					}
				}
			}
		};
	}

	private void initData() {
		list = new ArrayList<String>();
		list.add("星期一");
		list.add("星期二");
		list.add("星期三");
		list.add("星期四");
		list.add("星期五");
		list.add("星期六");
		list.add("星期日");
	}

	// 获取网络数据
	private void getData(final int code) {
		if (!NetWorkUtils.isActive(WeatherActivity.this)) {
			handler.sendEmptyMessage(404);
			return;
		}
		// 开启子线程进行网络请求数据，耗时操作不能在主线程中执行，必须在子线程中
		new Thread() {
			public void run() {
				String result = NetWorkUtils.doGet(url + code + ".html");
				if (TextUtils.isEmpty(result)) {
					handler.sendEmptyMessage(404);
					return;
				}
				Message message = handler.obtainMessage();
				message.what = 200;
				message.obj = parserJson(result);
				handler.sendMessage(message);
			}
		}.start();
	}

	// 解析天气预报字符串
	private List<WeatherBean> parserJson(String result) {
		List<WeatherBean> list = new ArrayList<WeatherBean>();
		if (!TextUtils.isEmpty(result)) {
			try {
				// 将JSON串转换为JSONObject对象
				JSONObject temp = new JSONObject(result);
				// 根据key获取value值，这里的value是一个JSONObject对象
				JSONObject weatherInfo = temp.getJSONObject("weatherinfo");
				for (int i = 1; i < 7; i++) {
					WeatherBean bean = new WeatherBean();
					if (i == 1) {
						// 城市
						bean.setCity(weatherInfo.getString("city"));
						// 日期
						bean.setDate_y(weatherInfo.getString("date_y"));
						// 当前温度
						bean.setTempCurrent(weatherInfo.getString("temp") + "°");
						// 当前风力风向
						bean.setWindCurrent(weatherInfo.getString("wd") + " " + weatherInfo.getString("ws"));
						bean.setPm("PM:" + weatherInfo.getString("pm") + " " + weatherInfo.getString("pm-level"));
					}
					// 设置一天的气温情况
					bean.setTemp(weatherInfo.getString("temp" + i));
					// 设置一天的天气情况
					bean.setWeather(weatherInfo.getString("weather" + i));
					// 设置一天的风的情况
					bean.setWind(weatherInfo.getString("wind" + i));
					// 设置日期是星期几
					bean.setWeek(getWeek(i, weatherInfo.getString("week")));
					// 将一天的数据情况添加到集合数据中
					list.add(bean);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return list;
	}

	// 循环得到当天以后属于星期几
	private String getWeek(int i, String week) {
		int index = 0;
		for (int j = 0; j < list.size(); j++) {
			if (list.get(j).equals(week)) {
				index = j;
				break;
			}
		}
		if (index + i < 8) {
			index = index + i - 1;
		} else {
			index = index + i - 8;
		}
		return list.get(index);
	}

	// 初始化View
	private void initView() {
		myButtonWeatherBack = (ImageButton) findViewById(R.id.myButtonWeatherBack);
		search_iv = (ImageButton) findViewById(R.id.search_iv);
		city_tv = (TextView) findViewById(R.id.city_tv);
		pm_tv = (TextView) findViewById(R.id.pm_tv);
		view_bottomLine = findViewById(R.id.view_bottomLine);
		error_tv = (TextView) findViewById(R.id.error_tv);
		temp_tv = (TextView) findViewById(R.id.temp_tv);
		weather_tv = (TextView) findViewById(R.id.weather_tv);
		wind_tv = (TextView) findViewById(R.id.wind_tv);
		date_tv = (TextView) findViewById(R.id.data_tv);
		other_ll = (LinearLayout) findViewById(R.id.other_ll);
	}

}

